package com.example.mykotlinapp

import com.example.mykotlinapp.util.joinToString
import java.io.BufferedReader
import java.lang.NumberFormatException
import java.util.*

/**
 *
 *
 * @author zhudeshuai
 * @since 2019/6/27
 */

//迭代map

private fun test01() {
    val binaryReps = TreeMap<Char, String>()
    for (c in 'A'..'F') {
        val binary = Integer.toBinaryString(c.toInt())
        binaryReps[c] = binary
    }
    for ((letter, binary) in binaryReps) {
        println("$letter = $binary")
    }
}

//迭代集合同时跟踪下标
private fun test02() {
    val list = arrayListOf("aaaa", "ccccc", "dddddd")
    for ((index, element) in list.withIndex()) {
        println("$index:$element")
    }
}

//区间检查

//是否是字母
private fun isLetter(c: Char) = c in 'a'..'z' || c in 'A'..'Z'

private fun isNotNumber(c: Char) = c !in '0'..'9'
private fun recognize(c: Char) {
    when (c) {
        in '0'..'9' -> println("$c is a number")
        in 'a'..'z', in 'A'..'Z' -> println("$c is a letter")
        else -> println("i don't know")
    }
}

//异常处理

private fun readNumber(reader: BufferedReader): Int? =
    try {
        val line = reader.readLine()
        Integer.parseInt(line)
    } catch (e: NumberFormatException) {
        null
    } finally {
        reader.close()
    }

//使用kotlin创建集合

val set = hashSetOf(1, 2, 3)
val map = hashMapOf(1 to "java", 2 to "C++", 3 to "C#")
val list = listOf(1, 2, 3)


//函数声明
/*
private fun <T> joinToString(
    collection: Collection<T>,
    separator: String = ",",
    prefix: String = "",
    postfix: String = ""
): String {
    val result = StringBuilder(prefix)
    for ((index, element) in collection.withIndex()) {
        if (index > 0) result.append(separator)
        result.append(element)
    }
    result.append(postfix)
    return result.toString()
}
*/


//顶层函数和属性

//扩展函数和属性,但是不能访问类的私有或者受保护的成员
private fun String.lastChar(): Char = this[this.length - 1]
val String.lastChar: Char
    get() = get(length - 1)

private fun main() {
    println("kotlin".lastChar())
    println("kotlin".lastChar)
    println(joinToString(set,","))

    println(list.last())
}


















